
//
// 110216 - AH - Created.
// 110216 - AH - (Garage) Made an AttributeObject.
// 110521 - AH - contains(char).
//

package org.soekrat.engine.visitor;

import java.util.StringTokenizer;

import org.soekrat.AttributeObject;


/**
 * <p>
 *   Represents a line entered from end user.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC) 
 */
public final class Line extends AttributeObject
{
  private final String m_text;

  /**
   * <p>
   *   Constructor.
   * </p>
   * @param text Text entered by visitor.
   */
  public Line(String text)
  {
    if (text==null)
    {
      throw new NullPointerException("text");
    }
    
    m_text=text.trim();
  }
  
  /**
   * <p>
   *   Gets text as visitor entered it.
   * </p>
   * @return Text.
   */
  public String getText(){ return m_text; }
  
  @Override
  public String toString(){ return m_text; }
  
  private TokenizedLine m_input=null;
  
  /**
   * <p>
   *   Gets input to Soekrat from visitor input. 
   * </p>
   * @return {@code input}.
   */
  public TokenizedLine getInput(){ return getInput(null); }
  
  /**
   * <p>
   *   Gets input to Soekrat from visitor input. 
   * </p>
   * @param input Where to <i>add</i> input (old content is kept). If 
   *              {@code null} return allocated.
   * @return {@code input} or allocated if {@code null} passed.
   */
  public TokenizedLine getInput(TokenizedLine input)
  {
    input=(input==null) ? new TokenizedLine() : input;
   
    if (m_input==null)
    {
      m_input=new TokenizedLine();
      
      StringBuilder sb=new StringBuilder();
      int n=m_text.length();
      for (int i=0; i<n; i++)
      {
        char c=m_text.charAt(i);
        if (Character.isLetter(c)) sb.append(Character.toLowerCase(c));
        else                       sb.append(' ');
      }
      
      StringTokenizer st=new StringTokenizer(sb.toString());
      while (st.hasMoreTokens()) m_input.add(st.nextToken());
    }
    
    input.addAll(m_input);
    
    return input;
  }
  
  /**
   * <p>
   *   Tells if contains given character.
   * </p>
   * @param c Character to look for.
   * @return {@code true} if does, {@code false} if does not.
   */
  public boolean contains(char c){ return m_text.indexOf(c)!=-1; }
  
}
